package com.ruoyi.web.controller.video.Utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.Msg;
import com.ruoyi.common.utils.SendSocketMsg;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.server.standard.SpringConfigurator;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.constant.RoomInfoGetTypeEnum;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.msg.KuaishouDanmuMsg;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.msg.KuaishouGiftMsg;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.msg.KuaishouLikeMsg;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.msg.KuaishouRoomStatsMsg;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.protobuf.PayloadTypeOuterClass;
import tech.ordinaryroad.live.chat.client.codec.kuaishou.protobuf.WebGiftFeedOuterClass;
import tech.ordinaryroad.live.chat.client.commons.base.msg.ICmdMsg;
import tech.ordinaryroad.live.chat.client.commons.base.msg.IMsg;
import tech.ordinaryroad.live.chat.client.kuaishou.client.KuaishouLiveChatClient;
import tech.ordinaryroad.live.chat.client.kuaishou.config.KuaishouLiveChatClientConfig;
import tech.ordinaryroad.live.chat.client.kuaishou.listener.IKuaishouMsgListener;
import tech.ordinaryroad.live.chat.client.kuaishou.netty.handler.KuaishouBinaryFrameHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j

public class SendKs {

    SendSocketMsg sendSocketMsg = SpringUtils.getBean(SendSocketMsg.class);

    Map<String, List<WebGiftFeedOuterClass.WebGiftFeed>> map = new HashMap<>();
    static Object lock = new Object();
    KuaishouLiveChatClient res;

    static SysUser sysUser;

    public void takeKsMsg(String roomId,SysUser sysUser,String cookie) {
        //String cookie ="did=web_ff3448c75caa5ebde7c37fd67a6fd12d; clientid=3; did=web_ff3448c75caa5ebde7c37fd67a6fd12d; client_key=65890b29; kpn=GAME_ZONE; kuaishou.live.bfb1s=ac5f27b3b62895859c4c1622f49856a4; userId=3382990064; kuaishou.live.web_st=ChRrdWFpc2hvdS5saXZlLndlYi5zdBKgAeSLwcsFJJGFAmcoF_9H28W9O91WCtlCaoJoNBdTybsihR7bJ4PDvLP184uCiyBgZ970clV4ZPmOvH4wqLN9pP3jR7Ln8TyE4WPbBZIjIzwOV7DqNwJ8DzVZ7ZYSscGGAT4yLkq-a5FiktMUnzZA8WHp1iLiI8YTSkE9fqkgFHdJBiltJnJvnB8azcgSh5C5c7OETDhkVW0g8d5H8_x-aqwaEoMRdS355EPfvO-WEFcOv_Ls2yIgnYfVykzUkUyBtQTei_3gkqjdJWg_ykcG8EnReKrDeBAoBTAB; kuaishou.live.web_ph=067e25f83167ff2b0e328243ce8726bae596; userId=3382990064";

        KuaishouLiveChatClientConfig config = null;
        if(StringUtils.isNotEmpty(cookie)){
            config = KuaishouLiveChatClientConfig.builder()
                    // .roomInfoGetType(RoomInfoGetTypeEnum.NOT_COOKIE)
                    .cookie(cookie)
                    .roomId(roomId)
                    .build();
        }else{
            config = KuaishouLiveChatClientConfig.builder()
                    // .roomInfoGetType(RoomInfoGetTypeEnum.NOT_COOKIE)
                    .roomId(roomId)
                    .build();
        }
        res = new KuaishouLiveChatClient(config, new IKuaishouMsgListener() {
            @Override
            public void onMsg(IMsg msg) {
                // log.debug("收到{}消息 {}", msg.getClass(), msg);
            }

            @Override
            public void onCmdMsg(PayloadTypeOuterClass.PayloadType cmd, ICmdMsg<PayloadTypeOuterClass.PayloadType> cmdMsg) {
                // log.debug("收到CMD消息{}", cmd);
            }

            @Override
            public void onOtherCmdMsg(PayloadTypeOuterClass.PayloadType cmd, ICmdMsg<PayloadTypeOuterClass.PayloadType> cmdMsg) {
               // log.debug("收到其他CMD消息 {}", cmd);
            }

            @Override
            public void onUnknownCmd(String cmdString, IMsg msg) {
               // log.debug("收到未知CMD消息 {}", cmdString);
            }

            @Override
            public void onDanmuMsg(KuaishouBinaryFrameHandler binaryFrameHandler, KuaishouDanmuMsg msg) {
                if (msg.getBadgeLevel() > 0) {
                    String badgeName = msg.getBadgeName();
                    if (StrUtil.isBlank(badgeName)) {
                        msg.getBadgeName();
                    }
                }
                Msg res = new Msg();
                res.setType("弹幕");
                res.setRoomId(binaryFrameHandler.getRoomId()+"");
                res.setNickname(msg.getUsername());
                res.setUid(msg.getUid());
                res.setContent(msg.getContent());
                sendSocketMsg.sendSocketMsg(sysUser.getUserId()+"",res );

                //log.info("{} 收到弹幕 [{}] {}({})：{}", binaryFrameHandler.getRoomId(), msg.getBadgeLevel() != 0 ? msg.getBadgeLevel() + msg.getBadgeName() : "", msg.getUsername(), msg.getUid(), msg.getContent());
            }

            @Override
            public void onGiftMsg(KuaishouBinaryFrameHandler binaryFrameHandler, KuaishouGiftMsg msg) {
                if (msg.getBadgeLevel() > 0) {
                    String badgeName = msg.getBadgeName();
                    if (StrUtil.isBlank(badgeName)) {
                        msg.getBadgeName();
                    }
                }

                String mergeKey = msg.getMsg().getMergeKey();
                map.computeIfAbsent(mergeKey, s -> new ArrayList<>()).add(msg.getMsg());

                if (msg.getGiftCount() > 0) {
                    Msg res = new Msg();
                    res.setType("礼物");
                    res.setRoomId(binaryFrameHandler.getRoomId()+"");
                    res.setNickname(msg.getUsername());
                    res.setUid(msg.getUid());
                    res.setContent(msg.getGiftName());
                    sendSocketMsg.sendSocketMsg(sysUser.getUserId()+"",res );
                    log.info("{} 收到礼物 [{}] {}({}) {} {}({})x{}({}) mergeKey:{},comboCount:{}, batchSize:{}", binaryFrameHandler.getRoomId(), msg.getBadgeLevel() != 0 ? msg.getBadgeLevel() + msg.getBadgeName() : "", msg.getUsername(), msg.getUid(), "赠送", msg.getGiftName(), msg.getGiftId(), msg.getGiftCount(), msg.getGiftPrice(), msg.getMsg().getMergeKey(), msg.getMsg().getComboCount(), msg.getMsg().getBatchSize());
                }
            }



        });

       /* res.addStatusChangeListener((evt, oldStatus, newStatus) -> {
            if (newStatus == ClientStatusEnums.CONNECTED) {
                // 连接成功10秒后发送弹幕
                ThreadUtil.execAsync(() -> {
                    ThreadUtil.sleep(10000);
                    res.sendDanmu("666666", new Runnable() {
                        @Override
                        public void run() {
                            log.warn("弹幕发送成功");
                        }
                    });
                });
            }
        });*/



    }



    //开始链接
    public void startSocket() throws InterruptedException{
        res.connect();

    }

    //暂停链接
    public void stopSocket(){
        res.destroy();
    }

    //获取客户端
    public KuaishouLiveChatClient getClinet(){
        return res;
    }

    //获取状态
    public int getStatus(){
        return res.getStatus().getCode();
    }

    //设置cookie
    public void setCookie(String cookie){ res.getConfig().setCookie(cookie); }


}
